package com.example.haiyang.controller;

import com.example.haiyang.common.GetTrueIp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Controller
public class BaseController {
    private Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Autowired
    private GetTrueIp getTrueIp;
    @Autowired
    private RedisTemplate redisTemplate;



    @RequestMapping
    public String index(HttpServletRequest request){
        logger.info("打开登陆页面[{}]",getTrueIp.getIpAddr(request));
        Random random = new Random();
        try {
            Integer number = (Integer)redisTemplate.opsForValue().get("HAIYANG:IP:"+getTrueIp.getIpAddr(request));
            if (number ==null){
                redisTemplate.opsForValue().set("HAIYANG:IP:"+getTrueIp.getIpAddr(request),1,300+random.nextInt(20),TimeUnit.SECONDS);
            }else if (number <30){
                //如果存在就增加1
                redisTemplate.opsForValue().set("HAIYANG:IP:"+getTrueIp.getIpAddr(request),number+1,300+random.nextInt(20),TimeUnit.SECONDS);
            }else {
                return "common/frequentip";
            }
        }catch (Exception e){
            logger.info("访问出现异常，访问ip[{}]",getTrueIp.getIpAddr(request));
            e.printStackTrace();
        }
        return "index";
    }

    @RequestMapping("/toLogin")
    public String toLogin(HttpServletRequest request){
        //logger.info("打开登陆页面[{}]",getTrueIp.getIpAddr(request));
        return "login/login";
    }

    @RequestMapping("/toRegister")
    public String toRegister(HttpServletRequest request){
        //logger.info("打开登陆页面[{}]",getTrueIp.getIpAddr(request));
        return "login/register";
    }



}
